package beerAgent;

public class FallingObject {
	
	public enum Direction{
		LEFT, 
		RIGHT,
		DOWN; 
	}
	
	private int length, startColumn, column, row, mapWidth, mapHeight = -1;
	private Direction dir;
	
	public FallingObject(int maxObjectSize, int minObjectSize, int mapWidth, boolean horizontalSpeed) {
		this.startColumn = (int) (Math.random() * mapWidth - 1);
		this.column = startColumn;
		this.length = minObjectSize + (int) (Math.random() * (1 + maxObjectSize - minObjectSize));
		this.row = 0;
		this.mapWidth = mapWidth; 
		
		if (horizontalSpeed) {
			int randomDir = (int) (Math.random() * 3);
			if(randomDir == 0) dir = Direction.LEFT;
			else if(randomDir == 1) dir = Direction.RIGHT;
			else dir = Direction.DOWN;
		} else{
			dir = Direction.DOWN; 
		}
	}
	
	public int getLength() {
		return length;
	}
	
	public int getStartcolumn() {
		return startColumn;
	}
	
	public int getColumn() {
		return column;
	}
	
	public int getRow() {
		return row;
	}
	
	public Direction getDirection() {
		return dir;
	}
	
	public void setRow(int row) {
		this.row = row;
	}
	
	public FallingObject copy(){
		FallingObject copy = new FallingObject(0, 0, mapWidth,false); 
		copy.length = this.length; 
		copy.column = this.column; 
		copy.startColumn = this.startColumn; 
		copy.row =-1; 
		copy.dir = this.dir;
		return copy; 
	}
	
	public void setColumn(int column) {
		this.column = column;
	}
	
	public void reset(){
		this.column = startColumn; 
		this.row = mapHeight;
	}
	
	public boolean atPosition(int row, int col) {
		if (this.row != row) {
			return false; 
		}
		for (int i = getColumn(); i < getColumn()+getLength(); i++) {
			int modi = modulus(i, mapWidth);
			if (modi == col) return true;
		}
		return false;
	}
	
	private static int modulus(int a, int b){
		while (a < 0) a += b;
		return a%b;
	}

	public boolean atColumn(int col) {
		for (int i = getColumn(); i < getColumn()+getLength(); i++) {
			int modi = modulus(i, mapWidth);
			if (modi == col) return true;
		}
		return false;
	}
	
	public void moveHorizontal(int steps){
		column = modulus(column + steps, mapWidth); 
	}

	public void drop() {
		row++; 
		switch (dir) {
		case LEFT:
			column--;
			return;
		case RIGHT:
			column++; 
			return;
		default:
			return;
		}
	}
	
	public static FallingObject getPlayer(int playerLength, int mapWidth, int mapHeight){
		FallingObject player = new FallingObject(playerLength, playerLength, mapWidth, false); 
		player.mapHeight = mapHeight-1; 
		player.startColumn = 10; 
		player.setColumn(player.startColumn); 
		player.setRow(mapHeight-1); 
		return player; 
	}
}
